import { Component, OnInit } from '@angular/core';
import { Store } from '@ngxs/store';
import { SystemAction, SystemSelector } from '../../store';
import { DemoAction, DemoSelector } from '../../store/demo';
import { compressToBase64 } from 'lz-string';
import { NzMessageService } from 'ng-zorro-antd/message';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe-decorator';

@Component({
  selector: 'app-setting',
  templateUrl: './setting.component.html',
  styleUrls: ['./setting.component.scss'],
})
export class SettingComponent implements OnInit {
  settingString: string = '';
  @AutoUnsubscribe() isLogin$ = this.store.select(SystemSelector.isLogin);

  param = {
    username: '',
    password: '',
  };
  mailAddr: string = '';

  constructor(
      private store: Store,
      private message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.store.select(SystemSelector.emailAddr).subscribe(r => {
      this.mailAddr = r || '';
    });
  }

  exportSetting() {
    let list = this.store.selectSnapshot(DemoSelector.list);
    let str = JSON.stringify(list);
    this.settingString = compressToBase64(str);
    this.copy(`导出成功，已复制到剪贴板`);
  }

  importSetting() {
    this.store.dispatch(new DemoAction.ImportSetting(this.settingString));
  }

  copy(title?: string) {
    this.store.dispatch(new SystemAction.Copy(this.settingString, title));
  }

  resetData() {
    this.store.dispatch(new DemoAction.ResetData());
  }

  export2Email() {
    if (!this.mailAddr || this.mailAddr.trim().length === 0) {
      this.message.info(`请输入邮箱地址`);
      return;
    }
    let list = this.store.selectSnapshot(DemoSelector.list);
    let str = JSON.stringify(list);
    let settingString = compressToBase64(str);
    let subject = `备份数据`;
    this.store.dispatch(new SystemAction.SaveEmailAddr(this.mailAddr));
    window.open(`mailto:${this.mailAddr}?subject=${subject}&body=${settingString}`);
  }

  importFromClipboard() {
    this.store.dispatch(new DemoAction.ImportFromClipboard());
  }

  login() {
    this.store.dispatch(new SystemAction.Login(this.param));
  }

  logout() {
    this.store.dispatch(new SystemAction.Logout());
  }
}
